package org.enhance.common.util.encryption;

import java.security.MessageDigest;

import org.enhance.common.exception.EnhanceRuntimeException;

/**
 * @author JiangGengchao
 * @classname EncryptUtil
 * @description
 * @date 2021-10-26
 **/
public class EncryptUtil {
	private EncryptUtil() {
		throw new IllegalStateException("Utility class");
	}

	/**
	 * 利用java原生的类实现Md5加密
	 *
	 * @param str 加密后的报文
	 * @return
	 *
	 */
	public static String getMd5(String str) {
		return digest(str, "MD5");
	}

	/**
	 * 利用java原生的类实现SHA256加密
	 *
	 * @param str 加密后的报文
	 * @return
	 *
	 */
	public static String getSha256(String str) {
		return digest(str, "SHA-256");
	}

	private static String digest(String str, String algorithm) {
		MessageDigest messageDigest;
		String encodestr;
		try {
			messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(str.getBytes("UTF-8"));
			encodestr = byte2Hex(messageDigest.digest());
		} catch (Exception e) {
			throw new EnhanceRuntimeException(e);
		}
		return encodestr;
	}

	/**
	 * 将byte转为16进制
	 *
	 * @param bytes
	 * @return
	 */
	private static String byte2Hex(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		String temp;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length() == 1) {
				// 1得到一位的进行补0操作
				stringBuffer.append("0");
			}
			stringBuffer.append(temp);
		}
		return stringBuffer.toString();
	}

//	private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
//	private static String byte2Hex(byte[] bytes) {
//		return bufferToHex(bytes, 0, bytes.length);
//	}
//	private static String byte2Hex(byte[] bytes, int m, int n) {
//		StringBuilder sb = new StringBuilder(2 * n);
//		int k = m + n;
//		for (int l = m; l < k; ++l) {
//			char c0 = hexDigits[((bytes[l] & 0xF0) >> 4)];
//			char c1 = hexDigits[(bytes[l] & 0xF)];
//			sb.append(c0);
//			sb.append(c1);
//		}
//		return sb.toString();
//	}

}
